const jwt = require('jsonwebtoken');

module.exports = () => {
  return async function adminAuth(ctx, next) {
    const tokenStr = ctx.get('Authorization');
    const token = tokenStr?.startsWith('Bearer ') ? tokenStr.slice(7) : null;

    if (!token) {
      ctx.status = 401;
      ctx.body = { code: 401, msg: 'Verification code expired or not found' };
      return;
    }

    let payload;
    try {
      payload = jwt.verify(token, ctx.app.config.jwt.secret);
    } catch (err) {
      ctx.status = 401;
      ctx.body = { code: 401, msg: 'Verification code expired or not found' };
      return;
    }

    const user = await ctx.model.User.findByPk(payload.id);
    console.log('user', user?.role);

    if (!user || user.role !== "1") {  // 注意类型，role 是字符串还是数字，需确认
      ctx.status = 403;
      ctx.body = { code: 403, msg: '无权限，只有管理员可访问' };
      return;
    }

    ctx.user = user;

    await next();
  };
};
